package com.slixils.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.slixils.demo.pojo.entity.Order;
import com.slixils.demo.pojo.entity.SeckillOrder;
import com.slixils.demo.pojo.entity.User;
import com.slixils.demo.service.GoodsService;
import com.slixils.demo.service.OrderService;
import com.slixils.demo.service.SeckillOrderService;
import com.slixils.demo.vo.GoodsVo;
import com.slixils.demo.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 秒杀商品表 前端控制器
 * </p>
 *
 * @author Helen
 * @since 2022-04-05
 */
@RestController
@RequestMapping("/seckillGoods")
public class SeckillGoodsController {
    @Autowired
    private SeckillOrderService itSeckillOrderService;
    @Autowired
    private GoodsService itGoodsService;
    @Autowired
    private OrderService orderService;

    @RequestMapping("/doSecKill")
    public String doSecKill(Model model, User user, Long userId) {
        model.addAttribute("user", user);
        GoodsVo goodsVo = itGoodsService.findGoodsVoByGoodsId(userId);
        if (goodsVo.getStockCount() < 1) {
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断是否重复抢购
        SeckillOrder seckillOrder = itSeckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", userId));
        if (seckillOrder != null) {
            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
            return "secKillFail";
        }
        Order tOrder = orderService.secKill(user, goodsVo);
        model.addAttribute("order", tOrder);
        model.addAttribute("goods", goodsVo);
        return "orderDetail";
    }

}

